package com.panshi.controller;


import com.panshi.api.IUserService;
import com.panshi.utils.MailUtils;
import com.panshi.utils.RedisUtils;
import com.panshi.vo.ResponseVO;
import com.panshi.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;
import redis.clients.jedis.Jedis;

@RestController
@Api(tags = "用户注册接口")
public class ZhuceController {//注册控制层

    @Autowired
    IUserService userService; //用户service层
    @Autowired
    RedisUtils redisUtils;

    //发送邮箱验证码
    @PostMapping("/sendcode")
    @ResponseBody
    public ResponseVO sendEmail(String userName,String type) {
        ResponseVO rs = new ResponseVO();
        //发送邮箱验证码
        String sendCode = MailUtils.createSimpleMail();
        //发送内容
        String content = "【有贝口腔网】验证码为："+sendCode+" ( 此验证码5分钟内有效，切勿将验证码告知他人 ),请在页面中输入完成验证，如有问题，请联系有贝口腔网客服。";
        try {
            MailUtils.sendMail(userName, "有贝口腔网"+type+"验证", content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将邮箱验证码存入redis中
        Jedis jedis = redisUtils.getJedis();
        System.out.println("邮箱验证码====="+sendCode);
        //NX Key不存在时才set EX是秒 PX是毫秒 300是key的有效期5分钟
        jedis.set(type+":"+userName,sendCode,"NX","EX",300);
        rs.setSuccess(true);
        rs.setMsg("验证码发送成功！请注意查收");
        return rs;
    }


    @PostMapping("/zhuceadd") //注册按钮
    @ResponseBody
    public ResponseVO addUser(String userName,String pwd,String code) {
        String type = "zhuce";
        ResponseVO rs = new ResponseVO();
        System.out.println("zhuceController/////"+userName+"===="+pwd+"===="+code);
        //拿出储存在redis中的短信验证码
        Jedis jedis = redisUtils.getJedis();
        String sendCode = jedis.get(type+":"+userName);
        System.out.println("邮箱验证码：===="+sendCode);
        //判断输入的短信验证码是否与发送的相同
        if(code.equals(sendCode)){
            UserVO userVO = new UserVO();
            userVO.setU_mail(userName);//注册的账号
            userVO.setU_password(pwd);
            //用户状态(0冻结/1禁用/2正常)
            userVO.setU_state(2);
            //初次注册时给用户随机生成昵称
            userVO.setU_name(MailUtils.createUname());
            //初次注册时给用户初始化个性签名
            userVO.setU_mark("这个人很懒，没有个性签名。");
            //初次注册时给用户默认头像
            userVO.setU_img_url("/img/defulthead.png");

            //调用用户增加
            userService.addUser(userVO);
            rs.setMsg("恭喜你，注册成功了");
            rs.setSuccess(true);
            rs.setState(200);
            UserVO nowUser = userService.findUserByEmail(userName);
            rs.setUserVO(nowUser);
        }else{
            rs.setMsg("您输入的短信验证码错误！请重试！");
            rs.setState(500);
            rs.setSuccess(false);
        }
        return rs;
    }
}
